import 'dart:convert';
import 'dart:math';

import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:uuid/uuid.dart';

class StringUtils {
  static StringUtils instance = StringUtils();

  ///手机格式验证
  bool isChinaPhoneLegal(String str) {
    if (str.length != 11) {
      return false;
    }
    return RegExp('^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[1-9])|(147,145))\\d{8}\$').hasMatch(str);
  }

  ///获取文件大小
  String getFileSize(int length) {
    if (length < 1024) {
      return "1KB";
    } else if (length < 1024 * 1024) {
      return "${length ~/ 1024}KB";
    } else {
      return "${length / 1024 ~/ 1024}M";
    }
  }

  ///获取文件名称
  String getFileName(String path) {
    if (path.isEmpty) {
      return "未知文件";
    } else {
      var strings = path.split("/");
      if (strings.isEmpty) {
        return "未知文件";
      }
      return strings[strings.length - 1];
    }
  }

  // md5 加密
  String generateMD5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }

  String getFileXXX(String path) {
    if (path.isEmpty) {
      return "未知文件";
    }
    return path.split(".").last;
  }

  String getRandomString(int len) {
    String scopeF = '123456789'; //首尾
    String scopeC = '0123456789'; //中间
    String result = '';
    for (int i = 0; i < len; i++) {
      if (i == 0 || i == len - 1) {
        result += scopeF[Random().nextInt(scopeF.length)];
      } else {
        result += scopeC[Random().nextInt(scopeC.length)];
      }
    }
    return result;
  }

  //获取随机4位+时间戳
  String getUUid(){
    String randomStr = Random().nextInt(10).toString();
    for (var i = 0; i < 3; i++) {
      var str = Random().nextInt(10);
      randomStr = randomStr + "$str";
    }
    var timeNumber = DateTime.now().millisecondsSinceEpoch;//时间
    var uuid = randomStr + "$timeNumber";
    return uuid;
  }

  ///UUid
  String randomUuid(){
    Uuid uuid = const Uuid();
    return uuid.v4();
  }
}
